package org.kkhweb.checkbook;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SignInActivity extends Activity {

	private SimpleJSONParser jsonParser;
	private SimpleHTTPClient httpClient;
	private	ProgressDialog dialog;
	private	EditText emailField;
	private	EditText passwordField;
	private Button submitButton;	
	private String email;
	private String password;

	private SharedPreferences settings;
	private Editor editor;
    public static final String PREFS_NAME = "MyCheckbookSettings";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.signin);
        this.restore_settings();	    
	    
        submitButton = (Button) findViewById(R.id.form_signin_button_submit);
        submitButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
        		emailField = (EditText) findViewById(R.id.form_signin_field_email);
            	email = emailField.getText().toString();
            	passwordField = (EditText) findViewById(R.id.form_signin_field_password);
            	password = passwordField.getText().toString();
            	
            	signInThread();
            }
        });
	}//End onCreate

	@Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
    	super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }

//SignIn Thread    
	protected void signInThread()
	{
		httpClient = new SimpleHTTPClient();
		
    	dialog = ProgressDialog.show(SignInActivity.this, "Logging In", 
                "Please wait...", false);  		    

	    new Thread() {
		    @Override
		    public void run()
		    {         
		    	httpClient.addFormData("email", email);
		    	httpClient.addFormData("password", password);
		    	httpClient.setUserAgent("MyCheckbook For Android");
		    	httpClient.setURL(Globals.buildURL("signin"));
		    	httpClient.sendRequest();
		        
		        handler.sendEmptyMessage(0);
		    }
	    }.start();
	}

//Handler for SignInThread    
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			dialog.dismiss();
    		
    		if(httpClient.hasError()) {
    			toast(httpClient.getError());
    		} else {
    			jsonParser = new SimpleJSONParser();
            	jsonParser.parse(httpClient.getResponse());
            	
                if(jsonParser.hasError()) {
            		editor.putBoolean("logged_in", false);                	
                    toast(jsonParser.getError());
                } else {
            		editor.putInt("user_id", jsonParser.getInt("user_id"));
            		editor.putString("user_name", jsonParser.getStr("user_name"));
            		editor.putBoolean("logged_in", true);
            		editor.commit();
            		toast("Logged In!");
            		finish();
                }
    		}
		}
	};	

	//Toast Messages    
    private void toast(String msg)
    {
    	Context context = getApplicationContext();
    	Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();    	
    }  	
	
	private void restore_settings()
	{
        settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        editor = settings.edit();        
	}	
	
}//End SignInActivity